package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GulimallFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1.整个请求在同一个线程中完成，可以自己在Controller里拿到request请求头，放入ThreadLocal里，这里在取出来
                //2。使用springBoot提供的RequestContextHolder对象获取，RequestContextHolder对象内部也是使用里ThreadLocal
                //3。ThreadLocal只能获取同一线程中的数据，异步feign调用时会获取不到request，共享数据会用不了
                //      解决办法，在调用异步前，把需要共享的数据set进去
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(requestAttributes == null){
                    return;
                }
                //获取到当前请求
                HttpServletRequest request = requestAttributes.getRequest();//老请求
                if(request == null){
                    return;
                }
                //同步请求头数据，Cookie
                //requestTemplate 新请求
                //将老请求到Cookie同步给新请求
                String cookie = request.getHeader("Cookie");
                requestTemplate.header("Cookie",cookie);
            }
        };
    }
}
